import axios from "axios";
import {Message, Notification, MessageBox} from 'element-ui';

// axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest';
// axios.defaults.headers.post['Content-Type'] = 'text/plain;charset=UTF-8';
// axios.defaults.headers['Access-Control-Allow-Origin'] = '*';
// axios.defaults.headers['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type';
// axios.defaults.headers['Access-Control-Allow-Methods'] = 'PUT,POST,GET,DELETE,OPTIONS';

let service = axios.create({
  baseURL : 'http://127.0.0.1:8888/api',
  timeout: 10000
});

// 请求拦截 可在请求头中加入token等
service.interceptors.request.use(config => {
  return config;
}, error => {
  console.log(error);
  return Promise.reject(error);
});

// 响应拦截 对响应消息作初步的处理
service.interceptors.response.use(resp => {
  if (resp.data) {

    const res = resp.data;
    if (res.code !== 10000) {
      Message({
        type: 'error',
        message: res.message || 'Error',
        duration: 5000
      });
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          // store.dispatch('user/resetToken').then(() => {
          //   location.reload()
          // })
        })
      }
      return Promise.reject(new Error(res.message || 'error'));
    }else {
      return  res;
    }

  } else {
    return resp;
  }
}, error => {
  console.log('err' + error);
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  });
  return Promise.reject(error)
});

export default service;


